<?php
namespace soa\partner\ane;

use artisan\cache;
use artisan\db;
use soa\partner\DeliveryCommon;

class MobileAddress extends BaseInformation
{
    /**
     * @param $waybillNos
     * @param string $cmPhone
     * @param string $cmId
     * @param string $empNo
     * @param string $type
     * @return array
     */
    public function getMobileAddressByWaybillNo($waybillNos, $cmPhone = '', $cmId = '', $empNo = '', $type = 'address')
    {
        if (empty($waybillNos) && !is_array($waybillNos))
            return [];

        if(('phone' == $type && 1 == count($waybillNos)) || !in_array($type,['address','phone'])){
            $type = 'address';  //type为phone不写入数据库,单条时写入数据库
        }

        $isEdit = 0;
        $return = $insertToDB = [];

        //1、从cache查数据
        if($cmPhone){
            $cacheKey = 'ane_address_info_' . $cmPhone . '-' . date('Y-m-d');
            $resultsFromCache = cache::connect('pda')->get($cacheKey);
            if(!empty($resultsFromCache) && is_array($resultsFromCache)){
                foreach($waybillNos as $waybillNo){
                    if(isset($resultsFromCache[$waybillNo]) && is_array($resultsFromCache[$waybillNo])){
                        $info = $this->getRequest($type,$waybillNo,$resultsFromCache[$waybillNo]);
                        if($info){
                            $return[$waybillNo] = $info;
                        }
                    }
                }

                $waybillNos = array_merge(array_diff($waybillNos,array_keys($return)));
            }
        }

        $resultsFromCache = isset($resultsFromCache) && is_array($resultsFromCache) && $resultsFromCache ? $resultsFromCache : [];

        //2、从数据库查数据
        if(!empty($waybillNos)){
            $resultsFromDb = $this->getByDB($waybillNos, $type);
        }

        if(!empty($resultsFromDb) && is_array($resultsFromDb)){
            foreach ($resultsFromDb as $waybillNo => $result) {
                $return[$waybillNo] = $this->getRequest($type,$waybillNo,$result);

                if(!empty($result['phone']) || !empty($result['address'])){
                    $isEdit = 1;
                    $resultsFromCache[$waybillNo] = !empty($resultsFromCache[$waybillNo])?$resultsFromCache[$waybillNo]:[];
                    $resultsFromCache[$waybillNo] = $this->getRequest('cache',$waybillNo,$resultsFromCache[$waybillNo],$result);
                }
            }

            $waybillNos = array_merge(array_diff($waybillNos, array_keys($resultsFromDb)));
            unset($resultsFromDb);
        }

        //3、从接口查数据
        if(!empty($waybillNos))
            $results = $this->getAddress($waybillNos);

        if (!empty($results)) {
            foreach ($results as $result) {
                $waybillNo = $result['waybill'];
                $info = $this->getRequest($type,$waybillNo,$result);
                if($info){
                    $return[$waybillNo] = $info;
                    $info = $info['info'];
                    $insertToDB[$waybillNo] = [
                        'waybill_no' => $waybillNo,
                        'cm_phone'   => !empty($cmPhone) ? $cmPhone : '',
                        'emp_no'     => !empty($empNo) ? $empNo : '',
                        'name'       => !empty($info['name']) ? $info['name'] : '',
                        'mobile'     => !empty($info['phone']) ? $info['phone'] : '',
                        'address'    => !empty($info['address']) ? $info['address'] : '',
                        'province'   => !empty($info['province']) ? $info['province'] : '',
                        'city'       => !empty($info['city']) ? $info['city'] : '',
                        'area'       => !empty($info['area']) ? $info['area'] : '',
                    ];
                }
                if(!empty($result['phone']) || !empty($result['address'])){
                    $isEdit = 1;
                    $resultsFromCache[$waybillNo] = !empty($resultsFromCache[$waybillNo])?$resultsFromCache[$waybillNo]:[];
                    $resultsFromCache[$waybillNo] = $this->getRequest('cache',$waybillNo,$resultsFromCache[$waybillNo],$result);
                }
            }

            unset($results);
            if('address' == $type && $insertToDB){
                $this->saveToDB(array_values($insertToDB));
            }
        }

        if(isset($cacheKey) && $isEdit && $resultsFromCache){
            cache::connect('pda')->set($cacheKey,$resultsFromCache);
            cache::connect('pda')->expireat($cacheKey, strtotime(date('Y-m-d') . ' + 1 day'));
        }

        return $return;
    }

    /**
     * @param $data
     * @param string $type
     * @return array
     */
    public function getByDB($data,$type = 'address')
    {
        if(empty($data))
            return [];

        $addressee = [];
        $chunk = array_chunk($data, 30);

        foreach ($chunk as $item) {
            if('phone' == $type){
                $result = db::connect('kd_pda')->table('tbl_delivery_list_ane')
                    ->select('waybill_no,mobile')->getAll(['waybill_no IN' => $item]);
            }else{
                $result = db::connect('kd_pda')->table('tbl_delivery_list_ane')
                    ->select('waybill_no,name,mobile,address,province,city,area')->getAll(['waybill_no IN' => $item]);
            }

            foreach ($result as $value) {
                if('phone' == $type){
                    if(empty($value['mobile'])){
                        continue;
                    }
                    $addressee[$value['waybill_no']] = [
                        'phone'    => $value['mobile'] ?: '',
                    ];
                }else {
                    $addressee[$value['waybill_no']] = [
                        'name'     => $value['name'] ?: '',
                        'phone'    => $value['mobile'] ?: '',
                        'address'  => $value['address'] ?: '',
                        'province' => $value['province'] ?: '',
                        'city'     => $value['city'] ?: '',
                        'area'     => $value['area'] ?: ''
                    ];
                }
            }
        }

        return $addressee;
    }

    /**
     * @param $waybillNos
     * @return array
     */
    public function getAddress($waybillNos)
    {
        $return = [];
        foreach($waybillNos as $waybillNo){
            $result = $this->send('queryEwbInfoService',[
                'ewbNo'   => $waybillNo,
            ]);
            if($result){
                $result['waybill'] = $waybillNo;
                $return[] = [
                    'waybill'  => $waybillNo,
                    'province' => !empty($result['province']) ? $result['province'] : '',
                    'city'     => !empty($result['city']) ? $result['city'] : '',
                    'area'     => !empty($result['district']) ? $result['district'] : '',
                    'address'  => !empty($result['address']) ? $result['address'] : '',
                    'phone'    => !empty($result['contact']) ? $result['contact'] : '',
                    'name'     => !empty($result['cusName']) ? $result['cusName'] : '',
                ];
            }
        }

        return $return;
    }

    /**
     * @param array $insertData
     * @return bool
     */
    protected function saveToDB(array $insertData)
    {
        (new DeliveryCommon())->logMobileAddress('ane',$insertData);
//        return db::connect('kd_pda')->table('tbl_delivery_list_ane')->insert($insertData);
    }

    /**
     * @param $type
     * @param $waybillNo
     * @param $data
     * @param array $dataEx
     * @return array
     */
    private function getRequest($type,$waybillNo,$data,$dataEx=[])
    {
        if('phone' == $type){
            if(empty($data['phone'])){
                return [];
            }
            return [
                'waybillNo' => (string)$waybillNo,
                'info'      => [
                    'phone' => !empty($data['phone']) && !in_array($data['phone'],['1**********'])? $data['phone'] : '',
                ]
            ];
        } elseif ('cache' == $type) {
            return [
                'name'     => !empty($data['name']) ? preg_replace("/[ ;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", '', $data['name']) : (!empty($dataEx['name']) ? preg_replace("/[ ;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", '', $dataEx['name']) : ''),
                'phone'    => !empty($data['phone']) ? $data['phone'] : (!empty($dataEx['phone']) ? $dataEx['phone'] : ''),
                'province' => !empty($data['province']) ? $data['province'] : (!empty($dataEx['province']) ? $dataEx['province'] : ''),
                'city'     => !empty($data['city']) ? $data['city'] : (!empty($dataEx['city']) ? $dataEx['city'] : ''),
                'area'     => !empty($data['area']) ? $data['area'] : (!empty($dataEx['area']) ? $dataEx['area'] : ''),
                'address'  => !empty($data['address']) ? $data['address'] : (!empty($dataEx['address']) ? $dataEx['address'] : ''),
            ];
        } else {
            if(empty($data['address'])){
                return [];
            }
            return [
                'waybillNo' => (string)$waybillNo,
                'info'      => [
                    'name'     => !empty($data['name']) ? preg_replace("/[ ;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", '', $data['name']) : '',
                    'phone'    => !empty($data['phone']) && !in_array($data['phone'],['1**********'])? $data['phone'] : '',
                    'province' => !empty($data['province']) ? $data['province'] : '',
                    'city'     => !empty($data['city']) ? $data['city'] : '',
                    'area'     => !empty($data['area']) ? $data['area'] : '',
                    'address'  => !empty($data['address']) ? $data['address'] : '',
                ]
            ];
        }
    }
}